package cn.wolfcode.luowowo.mgrsite.listener;

import cn.wolfcode.luowowo.article.domain.StrategyDetail;
import cn.wolfcode.luowowo.article.service.IStrategyDetailService;
import cn.wolfcode.luowowo.cache.key.RedisKey;
import cn.wolfcode.luowowo.cache.service.IStrategyStatsCacheService;
import cn.wolfcode.luowowo.cache.vo.StrategyStats;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;

import java.util.List;

/** mysql --> redis
 * 将文章统计对象迁移到redis缓存中
 */
@Component
public class HotDataInItListener implements ApplicationListener<ContextRefreshedEvent> {
    @Reference
    private IStrategyStatsCacheService strategyStatsCacheService;
    @Reference
    private IStrategyDetailService strategyDetailService;
    @Value("${hotData.init}")
    private boolean flag;

    public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {

        if(flag){
            System.out.println(" 执行数据迁移初始化");
            //把数据从mysql中查询出来
            List<StrategyDetail> details = strategyDetailService.list();

            for (StrategyDetail detail : details) {
                //封装成统计对象
                StrategyStats StrategyStats = new StrategyStats();
                StrategyStats.setDestId(detail.getDest().getId());
                StrategyStats.setDestName(detail.getDest().getName());
                StrategyStats.setTitle(detail.getTitle());

                StrategyStats.setStrategyId(detail.getId());
                StrategyStats.setViewnum(detail.getViewnum());
                StrategyStats.setFavornum(detail.getFavornum());
                StrategyStats.setReplynum(detail.getReplynum());
                StrategyStats.setSharenum(detail.getSharenum());
                StrategyStats.setThumbsupnum(detail.getThumbsupnum());
                //保存到Redis
                strategyStatsCacheService.setStrategyStats(StrategyStats);

                Long strateId = detail.getId();//文章的统计id
                //飙升排行榜数据初始化
                if (strategyStatsCacheService.notExistRank(RedisKey.STRATEGY_STATS_UP_SORT, strateId)) {
                    int num = detail.getViewnum() + detail.getReplynum();
                    strategyStatsCacheService.addRank(RedisKey.STRATEGY_STATS_UP_SORT, num, strateId);
                }

                //热门排行榜数据初始化
                if (strategyStatsCacheService.notExistRank(RedisKey.STRATEGY_STATS_HOT_SORT, strateId)) {
                    int num = detail.getFavornum() + detail.getThumbsupnum();
                    strategyStatsCacheService.addRank(RedisKey.STRATEGY_STATS_HOT_SORT, num, strateId);
                }
            }
        }
    }
}
